const httpRequest = require("@/common/httpRequest.js")
// npm install spark-md5
const SparkMD5 = require("@/utils/spark-md5.js")
import Cache from '@/js_sdk/min-cache/min-cache.js'
let tempFiles = null;

export default {
	/**
	 * 选择图片上传
	 * @param object opt  
	 * @param callable successCallback 成功执行方法 data 
	 * @param callable errorCallback 失败执行方法 
	 */
	chooseImage: function(opt, successCallback, errorCallback) {
		let that = this;
		if (typeof opt === 'string') {
			let url = opt;
			opt = {};
			opt.url = url;
		}
		let count = opt.count || 1,
			text = opt.type || '图片上传中',
			sizeType = opt.sizeType || ['compressed'],
			sourceType = opt.sourceType || ['album', 'camera'];
		uni.chooseImage({
			count: count, //最多可以选择的图片总数
			sizeType: sizeType, // 可以指定是原图还是压缩图，默认二者都有  
			sourceType: sourceType, // 可以指定来源是相册还是相机，默认二者都有  
			success: chooseImageRes => {
				uni.showLoading({
					title: text,
					mask: true,
				});
				console.log(chooseImageRes)
				tempFiles = chooseImageRes.tempFiles;
				// return false
				that.handleFiles(successCallback, errorCallback, 'image');
			}
		});
	},
	chooseVideo: function(opt, successCallback, errorCallback) {
		let that = this;
		// if (typeof opt === 'string') {
		// 	let url = opt;
		// 	opt = {};
		// 	opt.url = url;
		// }
		let sourceType = opt.sourceType || ['album', 'camera'],
			text = opt.type || '视频上传中';
		uni.chooseVideo({
			sourceType: sourceType, // 可以指定来源是相册还是相机，默认二者都有  
			success: chooseVideoRes => {
				uni.showLoading({
					title: text,
					mask: true,
				});
				console.log(chooseVideoRes);
				// tempFiles = chooseVideoRes.tempFiles;
				tempFiles = chooseVideoRes;
				// return false
				that.handleFiles(successCallback, errorCallback, 'video');
			}
		});
	},
	chooseRecorderManager: function(opt, successCallback, errorCallback) {
		uni.showLoading({
			title: opt.text,
			mask: true,
		});
		tempFiles = opt.url;
		this.handleFiles(successCallback, errorCallback, 'video');
	},
	handleFiles: function(successCallback, errorCallback, type) {
		console.log("执行了！！！")
		let that = this;
		let file;
		let filePath;
		if (type == 'image') {
			file = tempFiles.shift();
			filePath = file.path;
		} else {
			file = tempFiles.tempFilePath
			filePath = tempFiles.tempFilePath;
		}
		// 获取上传的文件后缀，然后后端生成随机 COS 路径地址
		that.getFileMd5(filePath, function(md5) {
			// const cache = new Cache()
			// let initConfig = cache.get('initConfig');
			let initConfig = uni.getStorageSync('initConfig')
			let data = {
				name: filePath,
				md5: md5
			};
			data.costoken = initConfig.uploaddata.multipart.costoken;
			that.getUploadInfo(data, function(err, info) {
				if (err) {
					uni.hideLoading();
					errorCallback && errorCallback(err);
					return false;
				}
				// 上传文件
				that.uploadFile({
					info: info,
					filePath: filePath,
					uploadUrl: initConfig.uploaddata.cdnurl
				}, function(err, fileUrl) {
					uni.hideLoading();
					if (err) {
						errorCallback && errorCallback(err);
						return false;
					}
					if (tempFiles.length > 0) {
						console.log("再次执行！！！")
						that.handleFiles(successCallback, errorCallback,type);
					}
					successCallback && successCallback(fileUrl);
				});
			});
		})
	},
	/**
	 * 获取cos直传参数
	 */
	getUploadInfo: function(data, callback) {
		httpRequest.request("/addons/cos/index/params", 'POST', data).then(res => {
			callback && callback(null, res.data);
		}).catch(err => {
			callback && callback(err);
		});
	},
	uploadFile: function(opt, callback) {
		let formData = opt.info;
		// 如果服务端用了临时密钥计算，需要传 x-cos-security-token
		if (opt.securityToken) formData['x-cos-security-token'] = formData.securityToken;
		
		console.log(formData,"aaaaaaaaaaaaaa");
		uni.uploadFile({
			url: opt.uploadUrl, //仅为示例，非真实的接口地址
			filePath: opt.filePath,
			name: 'file',
			formData: formData,
			success: (res) => {
				if (![200, 204].includes(res.statusCode)) return callback && callback(res);
				// let fileUrl = opt.uploadUrl + '/' + camSafeUrlEncode(opt.cosKey).replace(/%2F/g, '/');
				let fileUrl = opt.uploadUrl + '/' + opt.info.key;
				callback && callback(null, {
					url: '/' + opt.info.key,
					fullurl: fileUrl
				});
			},
			error(err) {
				callback && callback(err);
			},
		});
	},
	//获取文件MD5值
	getFileMd5: function(filePath, cb) {
		// uni.getFileInfo({
		// 	filePath: filePath,
		// 	digestAlgorithm: 'md5',
		// 	success: function(res) {
		// 		cb && cb(res.digest);
		// 	}
		// });
		uni.saveFile({
			tempFilePath: filePath,
			success: function(res) {
				var savedFilePath = res.savedFilePath;
				console.log(savedFilePath);
				uni.getFileInfo({
					filePath: savedFilePath,
					digestAlgorithm: 'md5',
					success: function(res) {
						console.log(res);
						cb && cb(res.digest);
					},
					complete: function(res) {
						console.log(res);
					}
				});
			}
		});
		// let blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
		// 	chunkSize = 10 * 1024 * 1024,
		// 	// chunkSize = 2,
		// 	chunks = Math.ceil(file.size / chunkSize),
		// 	currentChunk = 0,
		// 	spark = new SparkMD5.ArrayBuffer(),
		// 	fileReader = new FileReader();
		// fileReader.onload = function(e) {
		// 	spark.append(e.target.result);
		// 	currentChunk++;
		// 	if (currentChunk < chunks) {
		// 		loadNext();
		// 	} else {
		// 		cb && cb(spark.end());
		// 	}
		// };

		// fileReader.onerror = function() {
		// 	console.warn('文件读取错误');
		// };

		// function loadNext() {
		// 	let start = currentChunk * chunkSize,
		// 		end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize;

		// 	fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
		// }

		// loadNext();
	}

}